package com.xk.timerapp;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.FullScreenDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.DialogXRunnable;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.xk.timerapp.base.base.build.BaseActivityPortrait;
import com.xk.timerapp.base.base.build.CommonAdapter;
import com.xk.timerapp.base.base.build.SwitchButton;
import com.xk.timerapp.data.AlarmClock;
import com.xk.timerapp.data.AlarmClockDatabaseManager;
import com.xk.timerapp.databinding.ActivityMainBinding;
import com.xk.timerapp.databinding.ItemTimerBinding;
import com.xk.timerapp.spinner.NiceSpinner;
import com.xk.timerapp.utils.AlarmManagerUtil;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivityPortrait<ActivityMainBinding> {


    private List<String> sp_time;
    private List<String> sp_times;
    private List<String> sp_long_times;

    private List<AlarmClock> data;

    private CommonAdapter<ItemTimerBinding,AlarmClock> clockCommonAdapter;
    @Override
    protected void initData() {
        PermissionX.init(this).permissions(Manifest.permission.VIBRATE).request(new RequestCallback() {
            @Override
            public void onResult(boolean b, @NonNull List<String> list, @NonNull List<String> list1) {

            }
        });
        sp_time= new ArrayList<>();
        sp_times =new ArrayList<>();
        sp_long_times =new ArrayList<>();
        sp_times.add("2");
        sp_times.add("3");
        sp_times.add("5");
        sp_time.add("10");
        sp_time.add("5");
        sp_time.add("10");
        sp_time.add("15");
        sp_time.add("25");
        sp_time.add("30");
        sp_long_times.add("1");
        sp_long_times.add("2");
        sp_long_times.add("3");
        new Thread(new Runnable() {
            @Override
            public void run() {
                data = AlarmClockDatabaseManager.getInstance().alarmClockDao().getAllAlarmClocks();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        clockCommonAdapter.setData(data);
                    }
                });
            }
        }).start();
    }

    @Override
    protected void onclick() {
        bind.floatAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addTimer();
            }
        });
    }
    int check =0;
    private void addTimer(){
        FullScreenDialog.show(new OnBindView<FullScreenDialog>(R.layout.dialog_timeadd) {
            @Override
            public void onBind(FullScreenDialog dialog, View v) {
                TextView tv = v.findViewById(R.id.tv_cancel);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                EditText editText =v.findViewById(R.id.ed_name);
                NiceSpinner niceSpinner_time =v.findViewById(R.id.sp_time);
                niceSpinner_time.attachDataSource(sp_time);
                NiceSpinner niceSpinner_times =v.findViewById(R.id.sp_times);
                niceSpinner_times.attachDataSource(sp_times);
                NiceSpinner niceSpinner_Ltimes =v.findViewById(R.id.sp_long_time);
                niceSpinner_Ltimes.attachDataSource(sp_long_times);
                TimePicker timePicker = v.findViewById(R.id.tp_time);


                RadioGroup RadioGroup = v.findViewById(R.id.rg_state);
                RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(android.widget.RadioGroup group, int checkedId) {
                        if(checkedId == R.id.radioRingOnce){
                            check=0;
                            niceSpinner_time.setVisibility(View.INVISIBLE);
                            niceSpinner_times.setVisibility(View.INVISIBLE);
                        }else if(checkedId == R.id.radioRingOnWeekdays){
                            check=1;
                            niceSpinner_time.setVisibility(View.VISIBLE);
                            niceSpinner_times.setVisibility(View.VISIBLE);
                        }else{
                            check=2;
                            niceSpinner_time.setVisibility(View.VISIBLE);
                            niceSpinner_times.setVisibility(View.VISIBLE);
                        }
                    }
                });

                SwitchButton isvirck = v.findViewById(R.id.switchWidget);

                tv_voice =v.findViewById(R.id.tv_vioce);
                tv_voice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setVoice();
                    }
                });

                TextView tv_sure = v.findViewById(R.id.tv_sure);
                tv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = editText.getText().toString();
                        if(TextUtils.isEmpty(name)||TextUtils.isEmpty(muri)||TextUtils.isEmpty(muriname)){
                            PopTip.show("闹钟名称或则闹钟铃声未选择");
                            return;
                        }
                        boolean b = isvirck.isChecked();
                        int  index = niceSpinner_Ltimes.getSelectedIndex();
                        String playtime = sp_long_times.get(index);
                        int  index2 = niceSpinner_Ltimes.getSelectedIndex();
                        String time = sp_time.get(index2);
                        int  index3 = niceSpinner_Ltimes.getSelectedIndex();
                        String times = sp_times.get(index3);
                        int hour =timePicker.getHour();
                        int min = timePicker.getMinute();
                        AlarmClock alarmClock =new AlarmClock();
                        alarmClock.alarmName =name;
                        alarmClock.alarmHour = hour;
                        alarmClock.playtime = playtime;
                        alarmClock.alarmMinute = min;
                        alarmClock.alarmTimes = Integer.parseInt(times);
                        alarmClock.alarmMode = check+"";
                        alarmClock.alarmInterval = Integer.parseInt(time);
                        alarmClock.ringtoneName = muriname;
                        alarmClock.isopen = false;
                        alarmClock.vibrate = b;
                        alarmClock.ringtoneUrl = muri;
                        WaitDialog.show("正在添加闹钟");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                AlarmClockDatabaseManager.getInstance().alarmClockDao().insertAlarmClock(alarmClock);
                                data = AlarmClockDatabaseManager.getInstance().alarmClockDao().getAllAlarmClocks();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        WaitDialog.dismiss();
                                        PopTip.show("添加成功");
                                        dialog.dismiss();
                                        clockCommonAdapter.setData(data);
                                    }
                                });
                            }
                        }).start();

                    }
                });
            }
        });
    }
    TextView tv_voice;
    int EXTRA_RINGTONE_PICKED_URI=100;
    int REQUEST_CODE_RINGTONE_PICKER=50;
    private String muri,muriname;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_RINGTONE_PICKER && resultCode == RESULT_OK) {
            Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            if (uri != null) {
                muri = uri.toString();
                try {
                    muriname = getRingtoneNameFromUri(this, uri);
                }catch (Exception e){
                    muriname = "默认铃声";
                }
                if(tv_voice!=null){
                    tv_voice.setText("铃声: "+muriname);
                }
            }
        }
    }

    private String getRingtoneNameFromUri(Context context, Uri uri) {
        String[] projection = {MediaStore.Audio.Media.DISPLAY_NAME};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
            return cursor.getString(index);
        }
        return null;
    }

    private void setVoice(){
        Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "选择铃声");
        startActivityForResult(intent, REQUEST_CODE_RINGTONE_PICKER);
    }


    @Override
    protected void initPortraitView() {
        bind.rv.setLayoutManager(new LinearLayoutManager(this));
        clockCommonAdapter =new CommonAdapter<ItemTimerBinding, AlarmClock>(new ArrayList<>()) {
            @Override
            protected void show(ItemTimerBinding holder, int position, AlarmClock alarmClock) {
                String hour = String.format("%02d", alarmClock.alarmHour);
                String min = String.format("%02d", alarmClock.alarmMinute);
                holder.tvTime.setText(hour+":"+min);
                    holder.sbOpen.setChecked(alarmClock.isopen);
                      boolean vi =alarmClock.vibrate;
                      int modev =1;
                      if(vi){
                          modev=2;
                      }
                int finalModev = modev;
                holder.sbOpen.setmOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                        @Override
                        public void OnCheckedChanged(boolean isChecked) {
                            if(isChecked){
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        WaitDialog.show("加载中...");
                                        alarmClock.isopen = true;
                                        AlarmClockDatabaseManager.getInstance().alarmClockDao()
                                                .updateAlarmClock(alarmClock);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                WaitDialog.dismiss();
                                            }
                                        });
                                    }
                                }).start();
                                if(alarmClock.alarmMode.equals("0")){
                                    AlarmManagerUtil.setDailyAlarm(alarmClock);
                                }else{

                                }
                            }else{
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        WaitDialog.show("加载中...");
                                        alarmClock.isopen = false;
                                        AlarmClockDatabaseManager.getInstance().alarmClockDao()
                                                .updateAlarmClock(alarmClock);
                                        AlarmManagerUtil.cancelAlarm(c,alarmClock);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                WaitDialog.dismiss();
                                            }
                                        });
                                    }
                                }).start();

                            }
                        }
                    });
                    String n = alarmClock.alarmMode;
                    String modes="";
                    if(n.equals("0")){
                        modes = "响一次";
                    }else if(n.equals("1")){
                        modes = "工作日";
                    }else{
                        modes = "自定义";
                    }
                    holder.tvMode.setText(modes);
                    holder.main.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String[] str = {"删除","复制","修改"};
                            BottomMenu.show(str)
                                    .setMessage("闹钟")
                                    .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                                        @Override
                                        public boolean onClick(BottomMenu dialog, CharSequence text, int index) {
                                           if(index==0){
                                               WaitDialog.show("正在删除闹钟");
                                                new Thread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        AlarmClockDatabaseManager.getInstance().alarmClockDao()
                                                                .deleteAlarmClock(alarmClock);
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                WaitDialog.dismiss();
                                                                PopTip.show("删除成功");
                                                                AlarmManagerUtil.cancelAlarm(c,alarmClock);
                                                                data.remove(alarmClock);
                                                                clockCommonAdapter.notifyItemRemoved(position);
                                                            }
                                                        });
                                                    }
                                                }).start();
                                           }else if(index==1){
                                               WaitDialog.show("正在复制闹钟");
                                               new Thread(new Runnable() {
                                                   @Override
                                                   public void run() {
                                                       AlarmClock alarmClockCopy = new AlarmClock(alarmClock); // 使用复制构造函数复制对象
                                                       data.add(alarmClockCopy); // 将复制的对象添加到列表中
                                                       AlarmClockDatabaseManager.getInstance().alarmClockDao().insertAlarmClock(alarmClockCopy); // 插入到数据库
                                                       runOnUiThread(new Runnable() {
                                                           @Override
                                                           public void run() {
                                                               WaitDialog.dismiss();
                                                               PopTip.show("复制成功");
                                                               clockCommonAdapter.notifyDataSetChanged();
                                                           }
                                                       });
                                                   }
                                               }).start();

                                           }else {
                                                alterAlock(alarmClock);
                                           }
                                            return false;
                                        }
                                    });
                        }
                    });
            }
        };
        bind.rv.setAdapter(clockCommonAdapter);
    }
    private void alterAlock(AlarmClock alarmClock){
        FullScreenDialog.show(new OnBindView<FullScreenDialog>(R.layout.dialog_timeadd) {
            @Override
            public void onBind(FullScreenDialog dialog, View v) {
                TextView tv = v.findViewById(R.id.tv_cancel);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                EditText editText =v.findViewById(R.id.ed_name);
                NiceSpinner niceSpinner_time =v.findViewById(R.id.sp_time);
                niceSpinner_time.attachDataSource(sp_time);
                NiceSpinner niceSpinner_times =v.findViewById(R.id.sp_times);
                niceSpinner_times.attachDataSource(sp_times);
                NiceSpinner niceSpinner_Ltimes =v.findViewById(R.id.sp_long_time);
                niceSpinner_Ltimes.attachDataSource(sp_long_times);
                TimePicker timePicker = v.findViewById(R.id.tp_time);
                RadioGroup RadioGroup = v.findViewById(R.id.rg_state);
                RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(android.widget.RadioGroup group, int checkedId) {
                        if(checkedId == R.id.radioRingOnce){
                            check=0;
                            niceSpinner_time.setVisibility(View.INVISIBLE);
                            niceSpinner_times.setVisibility(View.INVISIBLE);
                        }else if(checkedId == R.id.radioRingOnWeekdays){
                            check=1;
                            niceSpinner_time.setVisibility(View.VISIBLE);
                            niceSpinner_times.setVisibility(View.VISIBLE);
                        }else{
                            check=2;
                            niceSpinner_time.setVisibility(View.VISIBLE);
                            niceSpinner_times.setVisibility(View.VISIBLE);
                        }
                    }
                });

                SwitchButton isvirck = v.findViewById(R.id.switchWidget);

                tv_voice =v.findViewById(R.id.tv_vioce);
                tv_voice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setVoice();
                    }
                });

                TextView tv_sure = v.findViewById(R.id.tv_sure);
                tv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = editText.getText().toString();
                        if(TextUtils.isEmpty(name)||TextUtils.isEmpty(muri)||TextUtils.isEmpty(muriname)){
                            PopTip.show("闹钟名称或则闹钟铃声未选择");
                            return;
                        }
                        boolean b = isvirck.isChecked();
                        int  index = niceSpinner_Ltimes.getSelectedIndex();
                        String playtime = sp_long_times.get(index);
                        int  index2 = niceSpinner_Ltimes.getSelectedIndex();
                        String time = sp_time.get(index2);
                        int  index3 = niceSpinner_Ltimes.getSelectedIndex();
                        String times = sp_times.get(index3);
                        int hour =timePicker.getHour();
                        int min = timePicker.getMinute();
                        alarmClock.alarmName =name;
                        alarmClock.alarmHour = hour;
                        alarmClock.playtime = playtime;
                        alarmClock.alarmMinute = min;
                        alarmClock.alarmTimes = Integer.parseInt(times);
                        alarmClock.alarmMode = check+"";
                        alarmClock.alarmInterval = Integer.parseInt(time);
                        alarmClock.ringtoneName = muriname;
                        alarmClock.isopen = false;
                        alarmClock.vibrate = b;
                        alarmClock.ringtoneUrl = muri;
                        WaitDialog.show("正在添加闹钟");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                AlarmClockDatabaseManager.getInstance().alarmClockDao().updateAlarmClock(alarmClock);
                                data = AlarmClockDatabaseManager.getInstance().alarmClockDao().getAllAlarmClocks();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        WaitDialog.dismiss();
                                        PopTip.show("添加成功");
                                        dialog.dismiss();
                                        clockCommonAdapter.setData(data);
                                    }
                                });
                            }
                        }).start();

                    }
                });
            }
        });
    }
}